package com.water.wfo.component.api.interceptor;

import com.water.wfo.component.api.filter.RequestFilter;
import com.water.wfo.component.api.utils.AuthUtils;
import com.water.wfo.component.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * packageName com.water.wfo.component.api
 *
 * @author
 * @className AuthenticationIntereptor(处以class为网)
 * @date 2025/1/16
 * @description T0D0
 */
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {

    private static final String TOKEN_NAME = "_TOKEN";
    private static final String TOKEN_KEY = "tokenkey";
    private static final String TGC = "TGC";

    public AuthenticationInterceptor(){}

    public static void saveCookie(String userId, String empCode, String deptCode, String deptNname){
        HttpServletRequest request = (HttpServletRequest)RequestFilter.getRequestMap().get();
        HttpServletResponse response = (HttpServletResponse)RequestFilter.getResponseMap().get();
        HttpSession session = request.getSession(true);
        StringBuffer sb = new StringBuffer(8);
        sb.append(session.getId()).append(",");
        sb.append(userId).append(",");
        sb.append(empCode).append(",");
        sb.append(deptCode).append(",");
        sb.append(deptNname).append(",");
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(System.currentTimeMillis());
        int millisecond = session.getMaxInactiveInterval() * 1000;
        c.add(14, millisecond);
        sb.append(c.getTimeInMillis());
        String finaltoken = sb.toString();
        String marshtoken = new String(Base64.encodeBase64String(toBytes(finaltoken)));
        Cookie cookied = getCookie();
        if (cookied != null) {
            cookied.setValue(marshtoken);
        } else {
            cookied = new Cookie("_TOKEN", marshtoken);
        }

        cookied.setPath("/");
        cookied.setDomain(".water.com");
        response.addCookie(cookied);
    }

    public static Cookie getCookie(){
        return getCookie("_TOKEN");
    }

    public static Cookie getCookie(String name) {
        if(StringUtil.isBlank(name)){
            return null;
        }else {
            HttpServletRequest request = (HttpServletRequest) RequestFilter.getRequestMap().get();
            Cookie[] cookies = request.getCookies();
            if(cookies != null && cookies.length > 0){
                for(int i = cookies.length-1;i>=0; --i){
                    if(name.equals(cookies[i].getName())){
                        return cookies[i];
                    }
                }

            }
            return null;
        }
    }
    public static byte[] toBytes(String finaltoken) {
        try {
            return finaltoken.getBytes("UTF-8");
        } catch (UnsupportedEncodingException var2) {
            log.error(var2.getMessage(), var2);
            return null;
        }
    }
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)){
            return true;
        }else {
            HandlerMethod hm = (HandlerMethod) handler;
            Object target = hm.getBean();
            String methodName = hm.getMethod().getName();
            Method method  = ReflectionUtils.findMethod(target.getClass(),methodName);
            String url = RequestFilter.getRemoteReqURLMap().get();
            if(!AuthUtils.isChecked(url)){
                return true;
            }else {
               HttpServletRequest request = (HttpServletRequest) RequestFilter.getResponseMap().get();
               if(null == request){
                   return  true;
               }else {
                   HttpSession session = request.getSession(true);
                   Cookie cookie = getCookie();
                   String paramToken = "";
                   String userId;
                   if(cookie != null){
                       userId = request.getParameter("token");
                       paramToken = userId;
                       if(StringUtil.isBlank(userId)){
                           paramToken = cookie.getValue();
                       }
                   }else {
                       userId = request.getParameter("token");
                       paramToken = userId;
                   }

                   paramToken = StringUtil.replace(paramToken, "-", "+");
                   paramToken = StringUtil.replace(paramToken, "_", "/");
                   userId = "";
                   String empCode = "";
                   String deptCode = "";
                   String deptName = "";
                   String pass;
                   if (StringUtil.isNotBlank(paramToken)) {
                       String sessionId = "";
                       long expireTime = 0L;

                       try {
                           pass = new String(Base64.decodeBase64(paramToken), "UTF-8");
                           String[] keys = pass.split(",");
                           sessionId = keys[0];
                           userId = keys[1];
                           empCode = keys[2];
                           if (StringUtil.isNotBlank(empCode)) {
                               deptCode = keys[3];
                               deptName = keys[4];
                               if (keys.length <= 5) {
                                   Calendar c = Calendar.getInstance();
                                   c.setTimeInMillis(System.currentTimeMillis());
                                   int millisecond = 3600000;
                                   c.add(14, millisecond);
                                   expireTime = c.getTimeInMillis();
                               } else {
                                   try {
                                       expireTime = Long.parseLong(keys[5]);
                                   } catch (Exception var25) {
                                       Calendar c = Calendar.getInstance();
                                       c.setTimeInMillis(System.currentTimeMillis());
                                       int millisecond = 3600000;
                                       c.add(14, millisecond);
                                       expireTime = c.getTimeInMillis();
                                   }
                               }

                           }
                       } catch (UnsupportedEncodingException var26) {
                           log.error(var26.getMessage(), var26);
                       }
                   }

                   Cookie tgcCookie = getCookie("TGC");
                   boolean needLogout = false;
                   if (tgcCookie == null || StringUtil.isEmpty(tgcCookie.getValue())) {
                       needLogout = true;
                   }

                   if (needLogout) {
                       session.invalidate();
                       saveCookie("", "", "", "");
                       return false;
                   } else if (StringUtil.isNotBlank(empCode) && !"null".equals(empCode) && null != empCode) {
                       return true;
                   } else {
                       return false;
                   }
               }
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
